/*******************************************************************************
 * copyright (c) 2009 - 2010 Simon Allen
 *
 * This file is part of Convex Media Converter.
 *
 * Convex Media Converter is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Convex Media Converter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with Convex Media Converter; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ******************************************************************************/


#include "mainwindow.h"

#include <cstdlib>
#include <iostream>
#include <sstream>

using namespace std;


MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::MainWindow)
{
	aboutDialog = NULL;
	preferences = NULL;
	convertDialog = NULL;

	userSettings = new PresetSettings(QSettings::UserScope, Preferences::SETTING_APPLICATION_ID,
				      Preferences::SETTING_APPLICATION_ID, this);

	preferences = new Preferences(userSettings, this);
	QString defaultOutputDir = userSettings->value(Preferences::SETTING_DEFAULT_OUTPUT_DIR, getenv("HOME")).toString();

	ui->setupUi(this);
	ui->label_outputDir->setText(defaultOutputDir);

	outputSettings.setOutputDir(defaultOutputDir);

	setWindowIcon(QIcon(CONVEX_LOGO));

	connect(ui->action_addFiles, SIGNAL(triggered()), this, SLOT(addInputFiles()));
	connect(ui->action_removeFiles, SIGNAL(triggered()), this, SLOT(removeInputFiles()));
	connect(ui->action_clearInputFiles, SIGNAL(triggered(bool)), this, SLOT(clearInputFiles()));
	connect(ui->action_convert, SIGNAL(triggered()), this, SLOT(convert()));
	connect(ui->action_quit, SIGNAL(triggered()), this, SLOT(close()));
	connect(ui->action_newPreset, SIGNAL(triggered()), this, SLOT(newPreset()));
	connect(ui->action_savePreset, SIGNAL(triggered()), this, SLOT(savePreset()));
	connect(ui->action_clearPreset, SIGNAL(triggered()), this, SLOT(clearPreset()));
	connect(ui->action_deletePreset, SIGNAL(triggered()), this, SLOT(deleteSelectedPreset()));
	connect(ui->action_revertPreset, SIGNAL(triggered()), this, SLOT(revertPreset()));
	connect(ui->action_preferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
	connect(ui->action_about, SIGNAL(triggered()), this, SLOT(about()));
	connect(ui->pushButton_addFiles, SIGNAL(clicked()), this, SLOT(addInputFiles()));
	connect(ui->pushButton_removeFiles, SIGNAL(clicked()), this, SLOT(removeInputFiles()));
	connect(ui->pushButton_clearFiles, SIGNAL(clicked()), this, SLOT(clearInputFiles()));
	connect(this, SIGNAL(resized(QResizeEvent)), this, SLOT(resizeInputFiles(QResizeEvent)));
	connect(ui->treeWidget_inputFiles, SIGNAL(customContextMenuRequested(const QPoint &)),
		this, SLOT(showInputFileContextMenu(const QPoint &)));
	connect(ui->comboBox_preset, SIGNAL(currentIndexChanged(QString)),
		this, SLOT(presetChanged(QString)));
	connect(ui->pushButton_newPreset, SIGNAL(clicked()), this, SLOT(newPreset()));
	connect(ui->comboBox_format, SIGNAL(currentIndexChanged(QString)),
		this, SLOT(formatChanged(QString)));
	connect(ui->comboBox_audioCodec, SIGNAL(currentIndexChanged(QString)),
		this, SLOT(audioCodecChanged(QString)));
	connect(ui->comboBox_videoCodec, SIGNAL(currentIndexChanged(QString)),
		this, SLOT(videoCodecChanged(QString)));
	connect(ui->comboBox_videoStandard, SIGNAL(currentIndexChanged(QString)),
		this, SLOT(videoStandardChanged(QString)));
	connect(ui->comboBox_aspect, SIGNAL(currentIndexChanged(QString)),
		this, SLOT(videoAspectChanged(QString)));
	connect(ui->pushButton_addCmdOptions, SIGNAL(clicked()), this,
		SLOT(addCmdOption()));
	connect(ui->pushButton_removeCmdOptions, SIGNAL(clicked()), this,
		SLOT(removeCmdOptions()));
	connect(ui->pushButton_clearCmdOptions, SIGNAL(clicked()), this,
		SLOT(clearCmdOptions()));
	connect(ui->pushButton_savePreset, SIGNAL(clicked()), this, SLOT(savePreset()));
	connect(ui->pushButton_clearPreset, SIGNAL(clicked()), this, SLOT(clearPreset()));
	connect(ui->pushButton_deletePreset, SIGNAL(clicked()), this, SLOT(deleteSelectedPreset()));
	connect(ui->pushButton_revertPreset, SIGNAL(clicked()), this, SLOT(revertPreset()));
	connect(ui->pushButton_outputDir, SIGNAL(clicked()), this, SLOT(selectOutputDir()));
	connect(ui->pushButton_quit, SIGNAL(clicked()), this, SLOT(close()));
	connect(ui->pushButton_convert, SIGNAL(clicked()), this, SLOT(convert()));

	setupFormats();
	setupAudioBitrates();
	setupAudioModes();
	setupAudioChannels();
	setupVideoStandards();
	setGeometry();
	setIcons();

	if (!QFileInfo(userSettings->fileName()).exists())
		syncGlobalSettings();

	ui->comboBox_preset->addItems(userSettings->childGroups());
	ui->comboBox_preset->setCurrentIndex(-1);

	statusLabel.setText("Input files: " + QString::number(inputFiles.size()));

	ui->statusBar->addPermanentWidget(&statusLabel);
}

MainWindow::~MainWindow()
{
	delete ui;

	ui = NULL;
}

void MainWindow::setupFormats()
{
	QList<QPair<QString, QString> > formatPairs = userSettings->getPairs(PresetSettings::FORMAT);

	for (QList<QPair<QString, QString> >::const_iterator iter = formatPairs.begin();
	iter != formatPairs.end(); iter++)
		ui->comboBox_format->addItem(iter->second);

	ui->comboBox_format->setCurrentIndex(-1);
}

void MainWindow::setupAudioBitrates()
{
	QList<QPair<QString, QString> > bitratePairs = userSettings->getPairs(PresetSettings::AUDIO_BITRATE);

	for (QList<QPair<QString, QString> >::const_iterator iter = bitratePairs.begin();
	iter != bitratePairs.end(); iter++)
		ui->comboBox_audioBitrate->addItem(iter->second);

	ui->comboBox_audioBitrate->setCurrentIndex(-1);
}

void MainWindow::setupAudioModes()
{
	QList<QPair<QString, QString> > modePairs = userSettings->getPairs(PresetSettings::AUDIO_MODE);

	for (QList<QPair<QString, QString> >::const_iterator iter = modePairs.begin();
	iter != modePairs.end(); iter++)
		ui->comboBox_audioMode->addItem(iter->second);

	ui->comboBox_audioMode->setCurrentIndex(-1);
}

void MainWindow::setupAudioChannels()
{
	QList<QPair<QString, QString> > channelPairs = userSettings->getPairs(PresetSettings::AUDIO_CHANNELS);

	for (QList<QPair<QString, QString> >::const_iterator iter = channelPairs.begin();
	iter != channelPairs.end(); iter++)
		ui->comboBox_audioChannels->addItem(iter->second);

	ui->comboBox_audioChannels->setCurrentIndex(-1);
}

void MainWindow::setupVideoStandards()
{
	QList<QPair<QString, QString> > standardPairs = userSettings->getPairs(PresetSettings::VIDEO_STANDARD);

	for (QList<QPair<QString, QString> >::const_iterator iter = standardPairs.begin();
	iter != standardPairs.end(); iter++)
		ui->comboBox_videoStandard->addItem(iter->second);

	ui->comboBox_videoStandard->setCurrentIndex(-1);
}

bool MainWindow::initCodecs()
{
	for (;;)
	{
		switch (setupEncoders(preferences->getFFmpegLocation()))
		{
			case -1:
				preferences->selectFFmpegLocation();

				break;

			case 0:
				return true;

			case 1:
				return false;
		}
	}
}

int MainWindow::setupEncoders(const QString ffmpegLoc)
{
	if (!QFile::exists(ffmpegLoc))
	{
		QString msg("In order to convert media files, Convex Media Converter "
			    "needs to know the location of the FFmpeg program file. "
			    "This file is currently invalid or does not exist."
			    "\n\nTo select the location of this program file, click Ok."
			    "\nClick Close to quit.");

		QMessageBox::StandardButton button = QMessageBox::warning(this, "No FFmpeg program found",
								     msg, QMessageBox::Close | QMessageBox::Ok);

		if (button == QMessageBox::Ok)
			return -1;

		else
			return 1;
	}

	detectCodecs();
	setupAudioEncoders();
	setupVideoEncoders();

	return 0;
}

void MainWindow::detectCodecs()
{
	QProcess ffmpeg(this);

	ffmpeg.start("ffmpeg", QStringList() << "-codecs");
	ffmpeg.waitForFinished();

	QString output = ffmpeg.readAllStandardOutput();

	output = output.mid(output.indexOf("------") + 7);
	output = output.left(output.indexOf("Note, the names of encoders") - 1);

	QStringList outputLines = output.split("\n");

	foreach (QString line, outputLines)
		codecsFound.append(line.mid(8, 16).trimmed());
}

void MainWindow::setupAudioEncoders()
{
	QList<QPair<QString, QString> > codecs = userSettings->getPairs(PresetSettings::AUDIO_CODEC);

	for (QList<QPair<QString, QString> >::const_iterator iter = codecs.begin();
	iter != codecs.end(); iter++)
	{
		if (codecSupported(iter->first))
			ui->comboBox_audioCodec->addItem(iter->second);
	}

	ui->comboBox_audioCodec->setCurrentIndex(-1);
}

void MainWindow::setupVideoEncoders()
{
	QList<QPair<QString, QString> > codecs = userSettings->getPairs(PresetSettings::VIDEO_CODEC);

	for (QList<QPair<QString, QString> >::const_iterator iter = codecs.begin();
	iter != codecs.end(); iter++)
	{
		if (codecSupported(iter->first))
			ui->comboBox_videoCodec->addItem(iter->second);
	}

	ui->comboBox_videoCodec->setCurrentIndex(-1);
}

void MainWindow::syncGlobalSettings()
{
	QSettings globalSettings(QSettings::SystemScope, "convex", "default");

	QStringList settingList = globalSettings.allKeys();

	foreach (QString setting, settingList)
		userSettings->setValue(setting, globalSettings.value(setting));
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
	QMainWindow::resizeEvent(event);

	emit resized(*event);
}

void MainWindow::resizeInputFiles(QResizeEvent event)
{
	if (event.oldSize().width() == -1)
		return;

	int diff = event.size().width() - event.oldSize().width();

	ui->treeWidget_inputFiles->setColumnWidth(0, ui->treeWidget_inputFiles->columnWidth(0) + diff);

	if (ui->treeWidget_inputFiles->columnWidth(0) < 75)
		ui->treeWidget_inputFiles->setColumnWidth(0, 75);
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
	event->acceptProposedAction();
}

void MainWindow::dropEvent(QDropEvent *event)
{
	QList<QUrl> urls = event->mimeData()->urls();
	QString nextFileName;
	QStringList newInputFiles;

	for (QList<QUrl>::const_iterator iter = urls.begin(); iter != urls.end(); iter++)
	{
		nextFileName = iter->toLocalFile();

		if (isMediaFile(nextFileName))
			newInputFiles << nextFileName;
	}

	addInputFiles(newInputFiles);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
	userSettings->setValue(Preferences::SETTING_GEOMETRY, saveGeometry());

	QWidget::closeEvent(event);
}

bool MainWindow::isMediaFile(QString fileName) const
{
	MediaInfo info;

	return info.Open(fileName.toStdString());
}

void MainWindow::setGeometry()
{
	if (userSettings->value(Preferences::SETTING_SAVE_WINDOW_GEOMETRY,
			    QVariant::fromValue(true).toBool()).toBool())
		restoreGeometry(userSettings->value(Preferences::SETTING_GEOMETRY).toByteArray());

	else
	{
		QDesktopWidget *desktop = QApplication::desktop();
		int x, y;

		// Calculate where to place application.
		x = (desktop->width() - width()) / 2;
		y = (desktop->height() - height()) / 2;
		y -= 50;

		move(x, y);

		desktop = NULL;
	}
}

void MainWindow::setIcons()
{
	ui->action_convert->setIcon(QIcon::fromTheme("go-next",
				    QApplication::style()->standardIcon(QStyle::SP_ArrowForward)));
	ui->action_addFiles->setIcon(QIcon::fromTheme("list-add"));
	ui->action_removeFiles->setIcon(QIcon::fromTheme("list-remove"));
	ui->action_clearInputFiles->setIcon(QIcon::fromTheme("edit-clear"));
	ui->action_quit->setIcon(QIcon::fromTheme("application-exit",
				 QApplication::style()->standardIcon(QStyle::SP_DialogCloseButton)));
	ui->action_newPreset->setIcon(QIcon::fromTheme("document-new",
				      QApplication::style()->standardIcon(QStyle::SP_FileIcon)));
	ui->action_savePreset->setIcon(QIcon::fromTheme("document-save",
							QApplication::style()->standardIcon(QStyle::SP_DialogSaveButton)));
	ui->action_clearPreset->setIcon(QIcon::fromTheme("edit-clear",
					QApplication::style()->standardIcon(QStyle::SP_DialogDiscardButton)));
	ui->action_deletePreset->setIcon(QIcon::fromTheme("edit-delete",
					 QApplication::style()->standardIcon(QStyle::SP_TrashIcon)));
	ui->action_revertPreset->setIcon(QIcon::fromTheme("document-revert",
					 QApplication::style()->standardIcon(QStyle::SP_DialogResetButton)));
	ui->action_preferences->setIcon(QIcon::fromTheme("preferences-desktop",
					QApplication::style()->standardIcon(QStyle::SP_ComputerIcon)));
	ui->action_about->setIcon(QIcon::fromTheme("help-about",
				  QApplication::style()->standardIcon(QStyle::SP_DialogHelpButton)));

	ui->pushButton_addCmdOptions->setIcon(QIcon::fromTheme("list-add"));
	ui->pushButton_removeCmdOptions->setIcon(QIcon::fromTheme("list-remove"));
	ui->pushButton_clearCmdOptions->setIcon(QIcon::fromTheme("edit-clear"));

	ui->pushButton_newPreset->setIcon(QIcon::fromTheme("document-new",
					  QApplication::style()->standardIcon(QStyle::SP_FileIcon)));
	ui->pushButton_savePreset->setIcon(QIcon::fromTheme("document-save",
					   QApplication::style()->standardIcon(QStyle::SP_DialogSaveButton)));
	ui->pushButton_clearPreset->setIcon(QIcon::fromTheme("edit-clear",
					    QApplication::style()->standardIcon(QStyle::SP_DialogDiscardButton)));
	ui->pushButton_deletePreset->setIcon(QIcon::fromTheme("edit-delete",
					     QApplication::style()->standardIcon(QStyle::SP_TrashIcon)));
	ui->pushButton_revertPreset->setIcon(QIcon::fromTheme("document-revert",
					     QApplication::style()->standardIcon(QStyle::SP_DialogResetButton)));
	ui->pushButton_outputDir->setIcon(QIcon::fromTheme("folder",
					  QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon)));

	ui->pushButton_addFiles->setIcon(QIcon::fromTheme("list-add"));
	ui->pushButton_removeFiles->setIcon(QIcon::fromTheme("list-remove"));
	ui->pushButton_clearFiles->setIcon(QIcon::fromTheme("edit-clear"));

	ui->pushButton_quit->setIcon(QIcon::fromTheme("application-exit",
				     QApplication::style()->standardIcon(QStyle::SP_DialogCloseButton)));
	ui->pushButton_convert->setIcon(QIcon::fromTheme("go-next",
					QApplication::style()->standardIcon(QStyle::SP_ArrowForward)));
}

void MainWindow::about()
{
	if (!aboutDialog)
		aboutDialog = new AboutDialog(this);

	aboutDialog->show();
	aboutDialog->raise();
	aboutDialog->setVisible(true);
}

void MainWindow::addInputFiles()
{
	QStringList files = QFileDialog::getOpenFileNames(this, "Select source file", getenv("HOME"), INPUT_FILTER);

	if (files.size() > 0)
		addInputFiles(files);

	statusLabel.setText("Input files: " + QString::number(inputFiles.size()));
}

void MainWindow::addInputFiles(const QStringList files)
{
	for (QStringList::const_iterator iter = files.begin(); iter != files.end(); iter++)
	{
		QFileInfo *nextFile = new QFileInfo(*iter);

		if (!inputFiles.contains(*nextFile))
		{
			// Remove this line and apparently it's unable to load the library?
			MediaInfo info;

			if (!info.Open(iter->toStdString()))
			{
				QMessageBox::critical(this, "Could not open media file", "The media file " +
						      *iter + " could not be opened.\n\nThis may mean the file "
						      "is corrupted or you do not have permisssion to access it.");
			}

			else
			{
				// Retrieve stream information
				if (info.Get(Stream_General, 0, "Format").empty())
				{
					QMessageBox::warning(this, "Could not extract media information",
							     "The media information for the file " + *iter +
							     " could not be read.\n\nThis may mean the file is"
							     " corrupted or you do not have permisssion to access it.");

					continue;
				}

				QTreeWidgetItem *nextItem = new QTreeWidgetItem(ui->treeWidget_inputFiles);

				nextItem->setText(0, nextFile->fileName());

				nextItem->setText(1, info.Get(MediaInfoDLL::Stream_General, 0, "Format").c_str());
				nextItem->setText(2, (QString::number(nextFile->size() / 1000000.0, 'f', 2) + " MB"));

				nextItem->setToolTip(0, *iter);
				ui->treeWidget_inputFiles->addTopLevelItem(nextItem);

				inputFiles << *nextFile;

				info.Close();
			}
		}
	}
}

void MainWindow::removeInputFiles()
{
	int index = -1;

	QList<QTreeWidgetItem *> list = ui->treeWidget_inputFiles->selectedItems();

	if (list.empty())
		QMessageBox::warning(this, "Cannot remove input file", "No input file has been selected.");

	else
	{
		for (QList<QTreeWidgetItem *>::const_iterator iter = list.begin(); iter != list.end(); iter++)
		{
			index = ui->treeWidget_inputFiles->indexOfTopLevelItem(*iter);

			ui->treeWidget_inputFiles->takeTopLevelItem(index);

			inputFiles.removeAt(index);
		}

		statusLabel.setText("Input files: " + QString::number(inputFiles.size()));
	}
}

void MainWindow::clearInputFiles()
{
	ui->treeWidget_inputFiles->clear();

	inputFiles.clear();


	statusLabel.setText("Input files: " + QString::number(inputFiles.size()));
}

void MainWindow::showProperties()
{
	FileProperties *fileProperties = new FileProperties(currentInputFile, this);

	fileProperties->show();
	fileProperties->raise();
	fileProperties->setVisible(true);
}

void MainWindow::showInputFileContextMenu(const QPoint &pos)
{
	QTreeWidgetItem *item = ui->treeWidget_inputFiles->itemAt(pos);

	if (item)
	{
		QModelIndex fileIndex = ui->treeWidget_inputFiles->indexAt(pos);
		QMenu *menu = new QMenu(ui->treeWidget_inputFiles);

		currentInputFile = inputFiles.at(fileIndex.row());

		menu->addAction("&Remove", this, SLOT(removeInputFiles()), QKeySequence("Alt+R"));
		menu->addAction(QIcon::fromTheme("preferences-desktop", QApplication::style()->standardIcon(
				QStyle::SP_ComputerIcon)),"&Properties", this, SLOT(showProperties()),
				QKeySequence("Alt+P"));

		menu->exec(QCursor::pos());
	}
}

void MainWindow::presetChanged(QString newPreset)
{
	clearPreset();

	QStringList mediaStreams;

	userSettings->beginGroup(newPreset);
	mediaStreams = userSettings->childGroups();

	ui->lineEdit_presetName->setText(newPreset);
	ui->comboBox_format->setCurrentIndex(ui->comboBox_format->findText(
			userSettings->getMatch(userSettings->value(PresetSettings::KEY_FORMAT).toString(),
					   PresetSettings::FORMAT)));

	if (mediaStreams.contains(PresetSettings::KEY_AUDIO_STREAM))
	{
		userSettings->beginGroup(PresetSettings::KEY_AUDIO_STREAM);

		ui->comboBox_audioCodec->setCurrentIndex(ui->comboBox_audioCodec->findText(
				userSettings->getMatch(userSettings->value(PresetSettings::KEY_CODEC).toString(),
						   PresetSettings::AUDIO_CODEC)));

		ui->comboBox_audioBitrate->setCurrentIndex(ui->comboBox_audioBitrate->findText(
				userSettings->getMatch(userSettings->value(PresetSettings::KEY_BITRATE).toString(),
						   PresetSettings::AUDIO_BITRATE)));

		ui->comboBox_audioMode->setCurrentIndex(ui->comboBox_audioMode->findText(
				userSettings->getMatch(userSettings->value(PresetSettings::KEY_MODE).toString(),
						   PresetSettings::AUDIO_MODE)));

		ui->comboBox_audioSampleRate->setCurrentIndex(ui->comboBox_audioSampleRate->findText(
				userSettings->value(PresetSettings::KEY_SAMPLE_RATE).toString()));

		ui->comboBox_audioChannels->setCurrentIndex(ui->comboBox_audioChannels->findText(
				userSettings->getMatch(userSettings->value(PresetSettings::KEY_CHANNELS).toString(),
						   PresetSettings::AUDIO_CHANNELS)));

		userSettings->endGroup();
	}

	if (mediaStreams.contains(PresetSettings::KEY_VIDEO_STREAM))
	{
		userSettings->beginGroup(PresetSettings::KEY_VIDEO_STREAM);

		ui->comboBox_videoCodec->setCurrentIndex(ui->comboBox_videoCodec->findText(
				userSettings->getMatch(userSettings->value(PresetSettings::KEY_CODEC).toString(),
						   PresetSettings::VIDEO_CODEC)));

		QString standard = userSettings->value(PresetSettings::KEY_STANDARD).toString();

		ui->comboBox_videoStandard->setCurrentIndex(ui->comboBox_videoStandard->findText(
				userSettings->getMatch(standard, PresetSettings::VIDEO_STANDARD)));

		ui->spinBox_videoBitrate->setValue(userSettings->value(PresetSettings::KEY_BITRATE).toInt());

		if (standard == OutputSettings::VIDEO_STANDARD_CUSTOM)
		{
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(userSettings->value(PresetSettings::KEY_FRAME_RATE).toString()));

			ui->spinBox_width->setValue(userSettings->value(PresetSettings::KEY_WIDTH).toInt());
			ui->spinBox_height->setValue(userSettings->value(PresetSettings::KEY_HEIGHT).toInt());
		}

		ui->comboBox_aspect->setCurrentIndex(ui->comboBox_aspect->findText(
				userSettings->getMatch(userSettings->value(PresetSettings::KEY_ASPECT).toString(),
						       PresetSettings::VIDEO_ASPECT)));

		userSettings->endGroup();
	}

	outputSettings.clearCmdOptions();

	ui->treeWidget_cmdOptions->clear();

	QString cmdString = userSettings->value(PresetSettings::KEY_CMD_OPTIONS).toString().simplified();

	if (!cmdString.isEmpty())
	{
		QStringList cmdList = cmdString.split(" -");

		foreach (QString cmd, cmdList)
		{
			string option, value;

			if (!cmd.startsWith('-'))
				cmd.insert(0, "-");

			istringstream cmdStream(cmd.toStdString());

			cmdStream >> option;

			if (option.empty())
				continue;

			cmdStream >> value;

			QTreeWidgetItem *newOption = new QTreeWidgetItem(ui->treeWidget_cmdOptions);

			newOption->setFlags(newOption->flags() | Qt::ItemIsEditable);
			newOption->setText(0, option.c_str());

			if (!value.empty())
				newOption->setText(1, value.c_str());

			ui->treeWidget_cmdOptions->addTopLevelItem(newOption);
		}

		outputSettings.setCmdOptions(cmdString);
	}

	userSettings->endGroup();
}

void MainWindow::formatChanged(QString newFormat)
{
	if (newFormat.isEmpty())
	{
		ui->comboBox_audioCodec->setEnabled(false);
		ui->comboBox_videoCodec->setEnabled(false);
	}

	else if (newFormat == OutputSettings::FORMAT_AUDIO_DESC)
	{
		ui->comboBox_audioCodec->setEnabled(true);
		ui->comboBox_videoCodec->setEnabled(false);
		ui->comboBox_videoStandard->setEnabled(false);

		ui->comboBox_videoCodec->setCurrentIndex(-1);
		ui->comboBox_videoStandard->setCurrentIndex(-1);
		ui->comboBox_frameRate->setCurrentIndex(-1);
		ui->comboBox_aspect->setCurrentIndex(-1);
		ui->spinBox_videoBitrate->setValue(0);
		ui->spinBox_width->setValue(0);
		ui->spinBox_height->setValue(0);

		ui->comboBox_audioCodec->removeItem(ui->comboBox_audioCodec->findText("None"));

		if (ui->comboBox_audioCodec->currentText() != "None")
			outputSettings.setExtension(userSettings->getMatch(ui->comboBox_audioCodec->currentText(),
								       PresetSettings::AUDIO_CODEC));
	}

	else
	{
		ui->comboBox_audioCodec->setEnabled(true);
		ui->comboBox_videoCodec->setEnabled(true);
		ui->comboBox_videoStandard->setEnabled(true);

		if (newFormat == OutputSettings::FORMAT_MPEGTS_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_TS);

		else if (newFormat == OutputSettings::FORMAT_MPEGPS_DESC ||
			 newFormat == OutputSettings::FORMAT_MPEG1_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_MPG);

		else if (newFormat == OutputSettings::FORMAT_OGV_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_OGG);

		else if (newFormat == OutputSettings::FORMAT_WMV_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_WMV);

		else if (newFormat == OutputSettings::FORMAT_MJPEG_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_MJP);

		else if (newFormat == OutputSettings::FORMAT_MKV_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_MKV);

		else if (newFormat == OutputSettings::FORMAT_RAW_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_RAW);

		else if (newFormat == OutputSettings::FORMAT_MPEG4_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_MP4);

		else if (newFormat == OutputSettings::FORMAT_FLASH_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_FLV);

		else if (newFormat == OutputSettings::FORMAT_AVI_DESC)
			outputSettings.setExtension(OutputSettings::EXTENSION_AVI);

		if (ui->comboBox_audioCodec->findText("None") == -1)
			ui->comboBox_audioCodec->insertItem(0, "None");
	}
}

void MainWindow::audioCodecChanged(const QString newCodec)
{
	if (newCodec == "None" || newCodec.isEmpty())
	{
		ui->audioTab->setEnabled(false);

		ui->comboBox_audioBitrate->setCurrentIndex(-1);
		ui->comboBox_audioMode->setCurrentIndex(-1);
		ui->comboBox_audioSampleRate->setCurrentIndex(-1);
		ui->comboBox_audioChannels->setCurrentIndex(-1);
	}

	else
	{
		QString extension;

		ui->audioTab->setEnabled(true);
		ui->comboBox_audioBitrate->setEnabled(true);
		ui->comboBox_audioMode->setEnabled(true);
		ui->comboBox_audioSampleRate->setEnabled(true);
		ui->comboBox_audioChannels->setEnabled(true);

		if (newCodec == OutputSettings::AUDIO_CODEC_MP2_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_MP2);
			extension = OutputSettings::EXTENSION_AUDIO_MP2;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::MP2_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(2);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_MP3_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_MP3);
			extension = OutputSettings::EXTENSION_AUDIO_MP3;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::MP3_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(1);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_AAC_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_AAC);
			extension = OutputSettings::EXTENSION_AUDIO_M4A;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::AAC_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(0);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_AC3_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_AC3);
			extension = OutputSettings::EXTENSION_AUDIO_AC3;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::AC3_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(1);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_VORBIS_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_VORBIS);
			extension = OutputSettings::EXTENSION_AUDIO_OGG;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::VORBIS_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(7);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_FLAC_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_FLAC);
			extension = OutputSettings::EXTENSION_AUDIO_FLAC;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::FLAC_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(1);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_WAV_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_WAV);
			extension = OutputSettings::EXTENSION_AUDIO_WAV;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::WAV_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(7);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_WMAV1_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_WMAV1);
			extension = OutputSettings::EXTENSION_AUDIO_WMA;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::WMAV1_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(1);
		}

		else if (newCodec == OutputSettings::AUDIO_CODEC_WMAV2_DESC)
		{
			outputSettings.setAudioCodec(OutputSettings::AUDIO_CODEC_WMAV2);
			extension = OutputSettings::EXTENSION_AUDIO_WMA;

			ui->comboBox_audioSampleRate->clear();
			ui->comboBox_audioSampleRate->addItems(OutputSettings::WMAV2_SAMPLE_RATES);
			ui->comboBox_audioSampleRate->setCurrentIndex(1);
		}

		if (ui->comboBox_format->currentText() == OutputSettings::FORMAT_AUDIO_DESC)
			outputSettings.setExtension(extension);
	}
}

void MainWindow::videoCodecChanged(const QString newCodec)
{
	if (newCodec == "None" || newCodec.isEmpty())
	{
		ui->videoTab->setEnabled(false);

		ui->comboBox_videoStandard->setCurrentIndex(-1);
		ui->spinBox_videoBitrate->setValue(0);
		ui->spinBox_width->setValue(0);
		ui->spinBox_height->setValue(0);
		ui->comboBox_frameRate->setCurrentIndex(-1);
		ui->comboBox_aspect->setCurrentIndex(-1);
	}

	else
	{
		ui->videoTab->setEnabled(true);

		outputSettings.setVideoCodec(userSettings->getMatch(newCodec,
					     PresetSettings::VIDEO_CODEC));
	}
}

void MainWindow::videoStandardChanged(const QString videoStandard)
{
	if (videoStandard == OutputSettings::VIDEO_STANDARD_CUSTOM_DESC)
	{
		ui->spinBox_videoBitrate->setEnabled(true);
		ui->spinBox_width->setEnabled(true);
		ui->spinBox_height->setEnabled(true);
		ui->comboBox_frameRate->setEnabled(true);
	}

	else
	{
		ui->spinBox_videoBitrate->setEnabled(false);
		ui->spinBox_width->setEnabled(false);
		ui->spinBox_height->setEnabled(false);
		ui->comboBox_frameRate->setEnabled(false);

		if (videoStandard == OutputSettings::VIDEO_STANDARD_576P_DESC)
		{
			ui->spinBox_videoBitrate->setValue(4000);
			ui->spinBox_width->setValue(720);
			ui->spinBox_height->setValue(576);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(25)));

			outputSettings.setVideoBitrate(4000);
			outputSettings.setWidth(720);
			outputSettings.setHeight(576);
			outputSettings.setFrameRate(25);
		}

		else if (videoStandard == OutputSettings::VIDEO_STANDARD_480P_DESC)
		{
			ui->spinBox_videoBitrate->setValue(4000);
			ui->spinBox_width->setValue(720);
			ui->spinBox_height->setValue(480);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(29.97)));

			outputSettings.setVideoBitrate(4000);
			outputSettings.setWidth(720);
			outputSettings.setHeight(480);
			outputSettings.setFrameRate(29.97);
		}

		else if (videoStandard == OutputSettings::VIDEO_STANDARD_720P_DESC)
		{
			ui->spinBox_videoBitrate->setValue(4000);
			ui->spinBox_width->setValue(1280);
			ui->spinBox_height->setValue(720);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(29.97)));

			outputSettings.setVideoBitrate(4000);
			outputSettings.setWidth(1280);
			outputSettings.setHeight(720);
			outputSettings.setFrameRate(29.97);
		}

		else if (videoStandard == OutputSettings::VIDEO_STANDARD_1080P_DESC)
		{
			ui->spinBox_videoBitrate->setValue(4000);
			ui->spinBox_width->setValue(1920);
			ui->spinBox_height->setValue(1080);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(29.97)));

			outputSettings.setVideoBitrate(4000);
			outputSettings.setWidth(1920);
			outputSettings.setHeight(1080);
			outputSettings.setFrameRate(29.97);
		}

		else if (videoStandard == OutputSettings::VIDEO_STANDARD_QVGA_DESC)
		{
			ui->spinBox_videoBitrate->setValue(1250);
			ui->spinBox_width->setValue(320);
			ui->spinBox_height->setValue(240);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(30)));

			outputSettings.setVideoBitrate(1250);
			outputSettings.setWidth(320);
			outputSettings.setHeight(240);
			outputSettings.setFrameRate(30);
		}

		else if (videoStandard == OutputSettings::VIDEO_STANDARD_VGA_DESC)
		{
			ui->spinBox_videoBitrate->setValue(1500);
			ui->spinBox_width->setValue(640);
			ui->spinBox_height->setValue(480);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(30)));

			outputSettings.setVideoBitrate(1500);
			outputSettings.setWidth(640);
			outputSettings.setHeight(480);
			outputSettings.setFrameRate(30);
		}

		else if (videoStandard == OutputSettings::VIDEO_STANDARD_SVGA_DESC)
		{
			ui->spinBox_videoBitrate->setValue(1750);
			ui->spinBox_width->setValue(800);
			ui->spinBox_height->setValue(600);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(30)));

			outputSettings.setVideoBitrate(1750);
			outputSettings.setWidth(800);
			outputSettings.setHeight(600);
			outputSettings.setFrameRate(30);
		}

		else if (videoStandard == OutputSettings::VIDEO_STANDARD_XGA_DESC)
		{
			ui->spinBox_videoBitrate->setValue(2000);
			ui->spinBox_width->setValue(1024);
			ui->spinBox_height->setValue(768);
			ui->comboBox_frameRate->setCurrentIndex(ui->comboBox_frameRate->findText(QString::number(30)));

			outputSettings.setVideoBitrate(2000);
			outputSettings.setWidth(1024);
			outputSettings.setHeight(768);
			outputSettings.setFrameRate(30);
		}

		else
		{
			ui->spinBox_videoBitrate->setValue(0);
			ui->spinBox_width->setValue(0);
			ui->spinBox_height->setValue(0);
			ui->comboBox_frameRate->setCurrentIndex(-1);

			outputSettings.setVideoBitrate(0);
			outputSettings.setWidth(0);
			outputSettings.setHeight(0);
			outputSettings.setFrameRate(0);
		}
	}
}

void MainWindow::videoAspectChanged(const QString newAspect)
{
	outputSettings.setAspect(userSettings->getMatch(newAspect,
				     PresetSettings::VIDEO_ASPECT));
}

void MainWindow::addCmdOption()
{
	QTreeWidgetItem *newOption = new QTreeWidgetItem(ui->treeWidget_cmdOptions);

	newOption->setFlags(newOption->flags() | Qt::ItemIsEditable);

	ui->treeWidget_cmdOptions->addTopLevelItem(newOption);
	ui->treeWidget_cmdOptions->setCurrentItem(newOption);
	ui->treeWidget_cmdOptions->setItemSelected(newOption, true);

	newOption->setText(0, "New option");

	ui->treeWidget_cmdOptions->editItem(newOption, 0);
}

void MainWindow::removeCmdOptions()
{
	int index = -1;
	QList<QTreeWidgetItem *> list = ui->treeWidget_cmdOptions->selectedItems();
	QString cmdOptions;

	if (list.empty())
		QMessageBox::warning(this, "Cannot remove command option", "No command option has been selected.");

	else
	{
		for (QList<QTreeWidgetItem *>::const_iterator iter = list.begin(); iter != list.end(); iter++)
		{
			index = ui->treeWidget_cmdOptions->indexOfTopLevelItem(*iter);

			ui->treeWidget_cmdOptions->takeTopLevelItem(index);
		}

		int numOptions = ui->treeWidget_cmdOptions->topLevelItemCount();

		for (int i = 0; i < numOptions; i++)
		{
			QTreeWidgetItem *option = ui->treeWidget_cmdOptions->topLevelItem(i);

			cmdOptions += option->text(0) + " " + option->text(1) + " ";
		}

		outputSettings.setCmdOptions(cmdOptions.simplified());
	}
}

void MainWindow::clearCmdOptions()
{
	ui->treeWidget_cmdOptions->clear();

	outputSettings.clearCmdOptions();
}

void MainWindow::selectOutputDir()
{
	QString dir = QFileDialog::getExistingDirectory(this, tr("Select Output Folder"),
			outputSettings.getOutputDir(), QFileDialog::ShowDirsOnly);

	if (!dir.isEmpty())
	{
		ui->label_outputDir->setText(dir);

		outputSettings.setOutputDir(dir);
	}
}

void MainWindow::showPreferences()
{
	preferences->readPresets();
	preferences->show();
	preferences->raise();
	preferences->setVisible(true);
}

void MainWindow::convert()
{
	if (inputFiles.empty())
	{
		QMessageBox::warning(this, "No input files", "There are no input files to convert.");

		return;
	}

	updateOutputSettings();

	if (checkValidSettings())
	{
		if (!convertDialog)
			convertDialog = new ConvertDialog(userSettings, this);

		convertDialog->show();
		convertDialog->raise();
		convertDialog->setVisible(true);

		convertDialog->convert(preferences->getFFmpegLocation(), inputFiles, outputSettings);
	}
}

void MainWindow::cancelConversion()
{
	if (convertDialog)
		convertDialog->close();
}

void MainWindow::updateOutputSettings()
{
	outputSettings.setPresetName(ui->lineEdit_presetName->text());
	outputSettings.setFormat(userSettings->getMatch(ui->comboBox_format->currentText(),
						    PresetSettings::FORMAT));

	updateAudioOutputSettings();
	updateVideoOutputSettings();
	updateCmdOptions();
}

void MainWindow::updateAudioOutputSettings()
{
	if (ui->comboBox_audioCodec->currentIndex() > -1)
		outputSettings.setAudio(true);

	else
		outputSettings.setAudio(false);

	outputSettings.setAudioBitrate(userSettings->getMatch(ui->comboBox_audioBitrate->currentText(),
							  PresetSettings::AUDIO_BITRATE).toInt());
	outputSettings.setAudioMode(userSettings->getMatch(ui->comboBox_audioMode->currentText(),
						       PresetSettings::AUDIO_MODE));
	outputSettings.setAudioSampleRate(ui->comboBox_audioSampleRate->currentText().toInt());
	outputSettings.setAudioChannels(userSettings->getMatch(ui->comboBox_audioChannels->currentText(),
					PresetSettings::AUDIO_CHANNELS).toFloat());
}

void MainWindow::updateVideoOutputSettings()
{
	if (ui->comboBox_videoCodec->currentIndex() > -1)
		outputSettings.setVideo(true);

	else
		outputSettings.setVideo(false);

	outputSettings.setVideoBitrate(ui->spinBox_videoBitrate->value());
	outputSettings.setWidth(ui->spinBox_width->value());
	outputSettings.setHeight(ui->spinBox_height->value());
	outputSettings.setFrameRate(ui->comboBox_frameRate->currentText().toFloat());
}

void MainWindow::updateCmdOptions()
{
	QString cmdOptions;
	int totalOptions = ui->treeWidget_cmdOptions->topLevelItemCount();

	for (int i = 0; i < totalOptions; i++)
	{
		QTreeWidgetItem *option = ui->treeWidget_cmdOptions->topLevelItem(i);

		option->setText(0, option->text(0).simplified());
		option->setText(1, option->text(1).simplified());

		if ((!option->text(0).isEmpty()) && (!option->text(1).isEmpty()))
			cmdOptions += option->text(0) + " " + option->text(1) + " ";

		else if (!option->text(0).isEmpty())
			cmdOptions += option->text(0) + " ";
	}

	cmdOptions = cmdOptions.simplified();

	outputSettings.setCmdOptions(cmdOptions);
}

bool MainWindow::checkValidSettings()
{
	bool valid = true;

	if (ui->label_outputDir->text().isEmpty())
	{
		valid = false;

		QMessageBox::warning(this, "No output directory selected",
				     "To convert media files, and output folder must first be selected.");
	}

	return valid;
}

void MainWindow::newPreset()
{
	clearPreset();

	ui->comboBox_preset->setCurrentIndex(-1);
	ui->lineEdit_presetName->clear();
	ui->lineEdit_presetName->setFocus();

	ui->tabWidget->setCurrentIndex(0);
}

void MainWindow::savePreset()
{
	if (ui->lineEdit_presetName->text().isEmpty())
	{
		QMessageBox::warning(this, "No Preset Name", "To save a preset, you must first enter a name.");

		return;
	}

	updateOutputSettings();
	userSettings->beginGroup(outputSettings.getPresetName());
	userSettings->setValue(PresetSettings::KEY_FORMAT, outputSettings.getFormat());

	if (outputSettings.hasAudio())
	{
		userSettings->beginGroup(PresetSettings::KEY_AUDIO_STREAM);
		userSettings->setValue(PresetSettings::KEY_CODEC, outputSettings.getAudioCodec());
		userSettings->setValue(PresetSettings::KEY_BITRATE, outputSettings.getAudioBitrate());
		userSettings->setValue(PresetSettings::KEY_MODE, outputSettings.getAudioMode());
		userSettings->setValue(PresetSettings::KEY_SAMPLE_RATE, outputSettings.getAudioSampleRate());
		userSettings->setValue(PresetSettings::KEY_CHANNELS, outputSettings.getAudioChannels());
		userSettings->endGroup();
	}

	else
		userSettings->remove(PresetSettings::KEY_AUDIO_STREAM);

	if (outputSettings.hasVideo())
	{
		userSettings->beginGroup(PresetSettings::KEY_VIDEO_STREAM);
		userSettings->setValue(PresetSettings::KEY_CODEC, outputSettings.getVideoCodec());

		QString standard = userSettings->getMatch(ui->comboBox_videoStandard->currentText(),
						      PresetSettings::VIDEO_STANDARD);

		userSettings->setValue(PresetSettings::KEY_STANDARD, standard);
		userSettings->setValue(PresetSettings::KEY_BITRATE, outputSettings.getVideoBitrate());

		if (standard == OutputSettings::VIDEO_STANDARD_CUSTOM)
		{
			userSettings->setValue(PresetSettings::KEY_WIDTH, outputSettings.getWidth());
			userSettings->setValue(PresetSettings::KEY_HEIGHT, outputSettings.getHeight());
			userSettings->setValue(PresetSettings::KEY_FRAME_RATE, outputSettings.getFrameRate());
		}

		else
		{
			userSettings->remove(PresetSettings::KEY_WIDTH);
			userSettings->remove(PresetSettings::KEY_HEIGHT);
			userSettings->remove(PresetSettings::KEY_FRAME_RATE);
		}

		userSettings->setValue(PresetSettings::KEY_ASPECT, outputSettings.getAspect());
		userSettings->endGroup();
	}

	else
		userSettings->remove(PresetSettings::KEY_VIDEO_STREAM);

	updateCmdOptions();

	userSettings->setValue(PresetSettings::KEY_CMD_OPTIONS, outputSettings.getCmdOptions());
	userSettings->setValue(PresetSettings::KEY_EXTENSION, outputSettings.getExtension());
	userSettings->endGroup();

	if (ui->comboBox_preset->findText(outputSettings.getPresetName()) == -1)
		ui->comboBox_preset->addItem(outputSettings.getPresetName());

	ui->comboBox_preset->setCurrentIndex(ui->comboBox_preset->findText(
			outputSettings.getPresetName()));
}

void MainWindow::clearPreset()
{
	ui->comboBox_format->setCurrentIndex(-1);
	ui->comboBox_audioCodec->setCurrentIndex(-1);
	ui->comboBox_videoCodec->setCurrentIndex(-1);
	ui->comboBox_audioBitrate->setCurrentIndex(-1);
	ui->comboBox_audioChannels->setCurrentIndex(-1);
	ui->comboBox_audioMode->setCurrentIndex(-1);
	ui->comboBox_audioSampleRate->setCurrentIndex(-1);
	ui->comboBox_videoStandard->setCurrentIndex(-1);
	ui->comboBox_frameRate->setCurrentIndex(-1);
	ui->comboBox_aspect->setCurrentIndex(-1);
	ui->spinBox_videoBitrate->setValue(0);
	ui->spinBox_width->setValue(0);
	ui->spinBox_height->setValue(0);
}

void MainWindow::deletePreset(const QString preset)
{
	int index = ui->comboBox_preset->findText(preset);

	userSettings->remove(preset);

	ui->comboBox_preset->removeItem(index);

	if (index == ui->comboBox_preset->count())
		ui->comboBox_preset->setCurrentIndex(index - 1);

	else
		ui->comboBox_preset->setCurrentIndex(index);

	if (ui->comboBox_preset->count() == 0)
	{
		clearPreset();

		ui->lineEdit_presetName->clear();
	}
}

void MainWindow::deleteSelectedPreset()
{
	userSettings->remove(ui->comboBox_preset->currentText());

	ui->comboBox_preset->removeItem(ui->comboBox_preset->currentIndex());
	ui->comboBox_preset->setCurrentIndex(-1);

	clearPreset();

	ui->lineEdit_presetName->clear();
}

void MainWindow::revertPreset()
{
	presetChanged(ui->lineEdit_presetName->text());
}
